﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class GameDataTableParser : IDisposable
{
    #region xorScale 异或因子
    /// <summary>
    /// 异或因子
    /// </summary>
    private byte[] xorScale = new byte[] { 45, 66, 38, 55, 23, 254, 9, 165, 90, 19, 41, 45, 201, 58, 55, 37, 254, 185, 165, 169, 19, 171 };//.data文件的xor加解密因子
    #endregion

    #region GameDataTableParser 构造函数
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="path"></param>
    public GameDataTableParser(string path)
    {
        byte[] buffer = null;

        //------------------
        //第1步：读取文件
        //------------------
        using (FileStream fs = new FileStream(path, FileMode.Open))
        {
            buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
        }

        //------------------
        //第2步：解压缩
        //------------------
        buffer = ZlibHelper.DeCompressBytes(buffer);

        //------------------
        //第3步：xor解密
        //------------------
        int iScaleLen = xorScale.Length;
        for (int i = 0; i < buffer.Length; i++)
        {
            buffer[i] = (byte)(buffer[i] ^ xorScale[i % iScaleLen]);
        }

        //------------------
        //第4步：解析数据到数组
        //------------------
        m_MemoryStream = new MMO_MemoryStream(buffer);

        m_Row = m_MemoryStream.ReadInt();
        m_Column = m_MemoryStream.ReadInt();
        Console.WriteLine("-------" + m_Row);
        Console.WriteLine("-------" + m_Column);
    }
    #endregion

    public int ReadInt()
    {
        return m_MemoryStream.ReadInt();
    }

    public string ReadUTF8()
    {
        return m_MemoryStream.ReadUTF8String();
    }

    #region 字段或属性

    /// <summary>
    /// 二进制数据
    /// </summary>
    private MMO_MemoryStream m_MemoryStream;

    /// <summary>
    /// 行数
    /// </summary>
    private int m_Row;

    /// <summary>
    /// 列数
    /// </summary>
    private int m_Column;

    /// <summary>
    /// 当前行号
    /// </summary>
    private int m_CurRowNo = 0;

    /// <summary>
    /// 是否结束
    /// </summary>
    public bool Eof
    {
        get
        {
            return m_CurRowNo == m_Row;
        }
    }
    #endregion

    #region Next 转到下一条
    /// <summary>
    /// 转到下一条
    /// </summary>
    public void Next()
    {
        if (Eof) return;
        m_CurRowNo++;
    }
    #endregion

    #region Dispose 释放
    /// <summary>
    /// 释放
    /// </summary>
    void IDisposable.Dispose()
    {
        if (m_MemoryStream != null)
        {
            Console.WriteLine("Dispose");
            m_MemoryStream.Dispose();
        }
    }
    #endregion
}
